package com.example.yichuangyun.ui.activity.business;

import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.EditorInfo;

import com.example.yichuangyun.R;
import com.example.yichuangyun.config.Constant;
import com.example.yichuangyun.databinding.ActivitySetSharePersonBinding;
import com.example.yichuangyun.http.HttpRespond;
import com.example.yichuangyun.http.MyObserver;
import com.example.yichuangyun.http.RetrofitHelper;
import com.example.yichuangyun.model.EventBusModel;
import com.example.yichuangyun.model.business.RequestSharePersonModel;
import com.example.yichuangyun.mvvm.base.BaseActivity;
import com.example.yichuangyun.mvvm.base.BaseViewModel;
import com.example.yichuangyun.ui.adapter.SetShareAdapter;
import com.example.yichuangyun.utils.CommonUtil;
import com.example.yichuangyun.utils.ToastHelper;
import com.example.yichuangyun.utils.treelist.Node;
import com.example.yichuangyun.utils.treelist.SetShareBean;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 设置共享人
 */
public class SetSharePersonActivity extends BaseActivity<ActivitySetSharePersonBinding, BaseViewModel> {

    private String id;
    private final List<Node> mData = new ArrayList<>();
    private SetShareAdapter mAdapter;
    private final List<String> chooseData = new ArrayList<>();

    @Override
    protected BaseViewModel bindModel() {
        return getViewModel(this, BaseViewModel.class);
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    public void initData() {
        initTitleBar(getString(R.string.set_share_person));
        Bundle bundle = getIntent().getExtras();
        if (null != bundle) {
            id = bundle.getString(Constant.businessIdKey);
        }
        mAdapter = new SetShareAdapter(SetSharePersonActivity.this, mData, 1);
        binding.recyclerView.setAdapter(mAdapter);
        getTreeData("");
    }

    private void getTreeData(String keyword) {
        showLoadingDialog();
        JSONObject requestDate = new JSONObject();
        try {
            requestDate.put("keyword", keyword);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), requestDate.toString());
        RetrofitHelper.getInstance().execute(RetrofitHelper.getService().getTreeData(requestBody), new MyObserver<SetShareBean>() {
            @Override
            protected void onSuccess(SetShareBean setShareBean) {
                if (setShareBean.getData().getName() != null) {
                    Node node = setShareBean.getData();
                    mData.add(new Node(node.getName(), node.getId(), node.getParentId(),
                            node.getIsDept(), node.getFullId(), node.getJobNumber(), node.getOrgId()));
                    initList(node.getChildren());
                    initList(node.getUserList());
                }

                if (chooseData.size() > 0) {
                    for (Node m : mData) {
                        for (String n : chooseData) {
                            if (m.getOrgId().equals(n)) {
                                m.setChecked(true);
                            }
                        }
                    }
                }
                mAdapter.addDataAll(mData, TextUtils.isEmpty(keyword) ? 1 : 10);
                dismissLoadingDialog();
            }

            @Override
            protected void onFail(Throwable e) {
                super.onFail(e);
                ToastHelper.show(e.getMessage() + "");
                dismissLoadingDialog();
            }
        });
    }

    @Override
    protected void initClick() {
        binding.tvConfirm.setOnClickListener(v -> {
            if (chooseData.size() > 0) {
                setSharePerson();
            } else {
                ToastHelper.show(getString(R.string.please_choose_share_person));
            }
        });

        mAdapter.setOnOnCheckListener(node -> {
            if (node.isChecked()) {
                chooseData.add(node.getOrgId());
            } else {
                chooseData.removeIf(s -> s.equals(node.getOrgId()));
            }

            if (chooseData.size() > 0) {
                String text = getString(R.string.choose_share_person_count, chooseData.size());
                binding.tvNum.setText(Html.fromHtml(text, Html.FROM_HTML_MODE_LEGACY));
            } else {
                binding.tvNum.setText(getString(R.string.hint_choose_please));
            }
        });

        binding.etSearch.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                // 关闭软键盘
                CommonUtil.closeKeyboard(SetSharePersonActivity.this);
                String content = binding.etSearch.getText().toString();
                mData.clear();
                getTreeData(content);
                return true;
            }
            return false;
        });

        binding.etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                binding.ivClear.setVisibility(editable.toString().length() == 0 ? View.GONE : View.VISIBLE);
            }
        });

        binding.ivClear.setOnClickListener(view -> {
            binding.etSearch.setText("");
            mData.clear();
            getTreeData("");
        });
    }

    /**
     * 设置共享人
     */
    private void setSharePerson() {
        showLoadingDialog();
        RequestSharePersonModel requestModel = new RequestSharePersonModel(id, chooseData);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new Gson().toJson(requestModel));
        RetrofitHelper.getInstance().execute(RetrofitHelper.getService().saveSharePerson(requestBody), new MyObserver<HttpRespond<String>>() {
            @Override
            protected void onSuccess(HttpRespond<String> stringHttpRespond) {
                if (Constant.SUCCESS == stringHttpRespond.code) {
                    EventBus.getDefault().post(new EventBusModel(Constant.refreshInformationDetail));
                    ToastHelper.show(getString(R.string.insert_share_person_success));
                    finish();
                } else {
                    ToastHelper.show(stringHttpRespond.msg);
                }
                dismissLoadingDialog();
            }

            @Override
            protected void onFail(Throwable e) {
                super.onFail(e);
                dismissLoadingDialog();
            }
        });
    }

    private void initList(List<Node> list) {
        if (list == null || list.size() == 0)
            return;
        for (int i = 0; i < list.size(); i++) {
            Node node = list.get(i);
            if (node.getIsLeave() != 1) {
                mData.add(new Node(node.getName(), node.getId(), node.getParentId(),
                        node.getIsDept(), node.getFullId(), node.getJobNumber(), node.getOrgId()));
            }
            if (node.getChildren() == null || node.getChildren().size() == 0) {
                initList(node.getUserList());
            } else {
                initList(node.getChildren());
            }
        }
    }
}